var router = require('koa-router')();
import excelToJson from "convert-excel-to-json";

import fs from 'fs';
import ByteBuffer from 'bytebuffer';
import path from 'path';
import asyncBusboy from '../common/parsefile';
import db from 'mime-db';
var uuid = require('node-uuid');
import util from 'util';


import api from '../api';
import config from '../config';

//ckeditor 上传图片
// router.post('/ckeditor-upload-image',async (ctx,next) => {
// 	var {CKEditor,CKEditorFuncNum,langCode} = ctx.request.query; 
// 	const {files, fields} = await asyncBusboy(ctx.req);
//     var file = files[0];

//     var filePath = uploadFile(file);

// 	ctx.body = `<script>window.parent.CKEDITOR.tools.callFunction(${CKEditorFuncNum},'${filePath}','')</script>`
// });


// //普通上传图片
// router.post('/upload-image',async (ctx,next) => {
//     var {file_type} = ctx.request.query
//     const {files, fields} = await asyncBusboy(ctx.req);
//     var file = files[0];
//     let pathName = uploadFile(file,file_type);
//     console.log('/upload-image--------',file_type);
//     console.log('/upload-image0--------',pathName);
//     let result = await ctx.uploadFile("/abs/web/common/upload-file",{file_type,pathName});
//     if (result.success) {
        
//         ctx.body = pathName;
//     }else{
//         ctx.body = result;
//     }
//     // ctx.body = uploadFile(file,file_type);
// });

// //普通上传
// router.post('/upload-file',async (ctx,next) => {

//     const {files, fields} = await asyncBusboy(ctx.req);
//     var file = files[0];
//     let result = uploadFile(file);

//     console.log('/upload-file==============',result);
//     console.log('.upload-file=============',ctx.request.host);
//     ctx.body = result;
// });

// function uploadFile(file){
//     var content = fs.readFileSync(file.path),
//      filename = file.filename;

//     var nonce_str = uuid.v4().replace(/-/g, ""),
//         dirname = `/resource/${nonce_str}`+filename.match(/.(\w+)$/)[0],
//         file_path = path.resolve(process.cwd(),`../${dirname}`);
//         console.log('test====================',file_path);
//         // console.log('test==========555555=====',Buffer.byteLength(fs.createReadStream(file_path)));
//     fs.writeFileSync(file_path, content);
//     return dirname;
// }

router.post("/upload" , async (ctx,next) => {
    var {file_type} = ctx.request.query;
    let {files, fields} = await asyncBusboy(ctx.req);
    file_type = file_type || fields.file_type;
    var file = files[0];
    let filesParams = [];
    files.forEach((item,index) => {
        filesParams.push({urlKey:'file',urlValue:item.path});
    })
    let result = await ctx.upload(`/abs/web/common/upload-file?file_type=${file_type}`,filesParams);
    if (result.success) {
        result.data.previewUrl = result.data.url;
    }
    console.log('test',result);

    ctx.body = result
})


export default router;